package br.uece.tcc.fh.jxta.util.message;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import br.uece.tcc.fh.facade.FhFacade;

import net.jxta.impl.protocol.ResolverResponse;
import net.jxta.protocol.ResolverQueryMsg;
import net.jxta.protocol.ResolverResponseMsg;
import net.jxta.resolver.ResolverService;

public class FhJxtaMessageHandle {

	 /**
     * The ResolverService used to handle queries and send responses.
     */
    private ResolverService resolver;


    /**
     * Create a new handler using the given ResolverService instance.
     *
     * @param   aResolver the ResolverService instance to use to 
     *          handle queries and send responses.
     */
    public FhJxtaMessageHandle(ResolverService aResolver)
    {
        this.resolver = aResolver;
    }

    /**
     * Processes the Resolver query message and returns a response. 
     *
     * @param       query the Resolver Query Message to be processed.
     * @return      an integer representing the success of processing,
     *              or need to repropagate the query.
     */
    public int processQuery(ResolverQueryMsg query)
    {
        ResolverResponse response;
        FhJxtaQueryMessage eq;
        
        String sqlResultSet = null;
        
        System.out.println("Processing query...");

        // Parse the message from the query string.
        try
        {
        	eq = new FhJxtaQueryMessage(
                new ByteArrayInputStream((query.getQuery()).getBytes()));
			System.out.println("Passou por aqui!!");
            // Perform the calculation.
            sqlResultSet = FhFacade.getInstance().find(eq.getSqlQuery()).toString();
            System.out.println("ResultSet processado!");
            System.out.println(sqlResultSet);
        
            // Create the response message.
            FhJxtaResponseMessage er = new FhJxtaResponseMessage(eq.getSqlQuery(),
                sqlResultSet);

            // Wrap the response message in a resolver response message.
            response = new ResolverResponse("FhJxtaMessageHandle",
                null, query.getQueryId(), er.toString());

            // Send the response using the resolver.
            resolver.sendResponse(query.getSrc(), response);

            // Signal that the resolver handled sending the response.
            System.out.println("OK!...");
            return resolver.OK;
        }
        catch (IOException e)
        {
            // Signal that the query should be repropagated.
            System.out.println("FUDEU!...");
            return resolver.Repropagate;
        }
    }

    /**
     * Process a Resolver response message.
     *
     * @param   response the Resolver Response Message to be processed.
     */
    public void processResponse(ResolverResponseMsg response)
    {
        FhJxtaResponseMessage er;
        
        System.out.println("Processing response...");

        try
        {
            // Extract the message from the Resolver response.
            er = new FhJxtaResponseMessage(
                new ByteArrayInputStream(
                    (response.getResponse()).getBytes()));
            
            // Print out the answer given in the response.
            System.out.println(
                "A consulta " + er.getSqlQuery() + " \nretornou a seguinte "+
                "resposta:\n\n" + er.getSqlResultSet() +"\n--------\n"); 
        }
        catch (IOException e)
        {
            // This is not the right type of response message, or
            // the message is improperly formed. Ignore the message,
            // do nothing.
        }
    }

}
